package com.chenfan.ccp.utils.sign;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

public class BlowfishUtil {
	private static Logger log = LoggerFactory.getLogger(BlowfishUtil.class);


	private static Key keyGenerator(String key) throws Exception {
		KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(key.getBytes());
		keyGenerator.init(128, secureRandom);
		return keyGenerator.generateKey();
	}

	/**
	 * 加密
	 *
	 * @param data 加密的参数
	 * @param key  加密的密钥
	 * @return
	 */
	public static String encrypt(String data, String key) {
		try {
			Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, keyGenerator(key));
			return bytes2HexString(cipher.doFinal(data.getBytes()));
		} catch (Exception e) {
			log.error("blowfish加密失败", e);
			return "";
		}
	}


	/**
	 * 解密
	 *
	 * @param data 解密的参数
	 * @param key  解密的密钥
	 * @return
	 */
	public static String decrypt(String data, String key) {
		try {
			Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, keyGenerator(key));
			return new String(cipher.doFinal(hexStringToBytes(data)));
		} catch (Exception e) {
			log.info("blowfish解密失败");
			return "";
		}
	}

	private static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	private static String bytes2HexString(byte[] b) {
		String a = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}

			a = a + hex;
		}
		return a;
	}


}

